<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Requests\Dashboard\CareerIndexRequest;
use App\Http\Requests\Dashboard\CareerStoreRequest;
use App\Http\Requests\Dashboard\CareerUpdateRequest;

use App\Http\Resources\Dashboard\CareerResource;

use App\Http\Resources\Dashboard\CareerAutoCompleteResource;
use App\Models\Career;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CareerController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param \App\Http\Requests\Dashboard\CareerIndexRequest $request
     * @param \App\Models\Career $career
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(CareerIndexRequest $request, Career $career)
    {

        if ($request->filled('title')) {
            $career = $career->like('title', $request->title);
        }
        if ($request->filled('description')) {
            $career = $career->like('description', $request->description);
        }
        if ($request->has('trashed')) {
            $career = $career->trashedType($request->trashed);
        }
        $career = $career->withCount('skills');
        return CareerResource::collection($career->paginate($request->get('per_page', 15)));
    }

    public function autoComplete(Request $request, Career $career)
    {

        if ($request->filled('keyword')) {
            $career = $career->like('title', $request->keyword)->orLike('description', $request->keyword);
        }

        $career = $career->limit($request->get('limit', 5));
        return CareerAutoCompleteResource::collection($career->get());
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \App\Http\Requests\Dashboard\CareerStoreRequest $request
     * @return \App\Http\Resources\Dashboard\CareerResource
     */
    public function store(CareerStoreRequest $request)
    {
        $career = new Career($request->only(['title', 'description']));
        $career->save();

        return new CareerResource($career);
    }

    /**
     * Display the specified resource.
     *
     * @param \App\Models\Career $career
     * @return \App\Http\Resources\Dashboard\CareerResource
     */
    public function show(Career $career)
    {
        return new CareerResource($career);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \App\Http\Requests\Dashboard\CareerUpdateRequest $request
     * @param \App\Models\Career $career
     * @return void
     */
    public function update(CareerUpdateRequest $request, Career $career)
    {
        $career->fill($request->only(['title', 'description']));
        $career->save();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param \App\Models\Career $career
     * @return void
     * @throws \Exception
     */
    public function destroy(Career $career)
    {
        $career->delete();
    }
}
